Parsing in <ctime>

The C++ <ctime> is inherited from C language and primarily uses the time_t data type to represent time.

1. Converting date-time string to time_t type.

It is a function to parse a date or time string.

Syntax:

time_t parseDateTime(const char* datetimeString, const char* format);

Here,

  • time_t: It is an arithmetic type that is used to represent time in C++.
  • parseDateTime: User-defined name of our function.
  • dateTimeString: Parameter which represents the current date and time in human-readable form.
  • format: The fashion in which dateTimeString is represented.

2. Converting time_t arithmetic type to string

Function to format a time_t value into a date or time string.

Syntax:

string formatDateTime(time_t time, const char* format)

Here,

  • string: return type of
  • time: It is time in time_t format.
  • datetimeString: String representing date and time.
  • format: format of the datetime string.

C++ Program:

C++




// C++ Program to implement Date and Time parsing using
// <ctime>
#include <ctime>
#include <iostream>
using namespace std;
 
// function to parse a date or time string.
time_t parseDateTime(const char* datetimeString, const char* format)
{
    struct tm tmStruct;
    strptime(datetimeString, format, &tmStruct);
    return mktime(&tmStruct);
}
 
// Function to format a time_t value into a date or time string.
string DateTime(time_t time, const char* format)
{
    char buffer[90];
    struct tm* timeinfo = localtime(&time);
    strftime(buffer, sizeof(buffer), format, timeinfo);
    return buffer;
}
int main()
{
    const char* datetimeString = "2023-06-17 12:36:51";
    const char* format = "%Y-%m-%d %H:%M:%S";
    time_t parsedTime = parseDateTime(datetimeString, format);
    string formattedTime = DateTime(parsedTime, format);
    cout << "Parsed Time--> " << parsedTime << endl;
    cout << "Formatted Time--> " << formattedTime << endl;
    return 0;
}


Output

Parsed Time--> 1687005411
Formatted Time--> 2023-06-17 12:36:51

Date and Time Parsing in C++

The Date and time parsing is a common task in programming especially when dealing with user input or data from external sources. C++ provides various utilities and libraries to handle date and time parsing efficiently. Some of the most commonly used libraries for date and time parsing in C++ are:

  1. <ctime>: This header provides functions and types to work with date and time values including parsing and formatting.
  2. <chrono>: This header provides facilities to deal with the duration time points and clocks. It is part of the C++11 standard and provides a more modern and type-safe approach to handling date and time operations.

Similar Reads

Parsing in

The C++ is inherited from C language and primarily uses the time_t data type to represent time....

Parsing in

...

Conclusion

The library was introduced in C++11 and provides a modern solution for time manipulation in C++....

Frequently Asked Questions (FAQs)

...